<template>
  <div class="inventoryBalance">
    <div class="publicSearch">
      <div class="searchBar" :style="{ height: isMoreSearch ? 'auto' : '' }">
        <el-button-group>
          <el-button @click="getInventoryBalanceData" size="mini" icon="el-icon-search">查询</el-button>
          <el-button @click="clearSearchData" size="mini" icon="el-icon-refresh">重置</el-button>
        </el-button-group>
        <div>
          <span>物料名称</span>
          <el-input v-model="searchData.itemName" size="mini" placeholder="物料名称" clearable></el-input>
        </div>
        <div>
          <span>物料编码</span>
          <el-input v-model="searchData.itemCode" size="mini" placeholder="物料编码" clearable></el-input>
        </div>
<!--        <div>-->
<!--          <span>货位</span>-->
<!--          <el-input v-model="searchData.cellCode" size="mini" placeholder="货位" clearable></el-input>-->
<!--        </div>-->
         <div >
          <span >仓库</span>
          <el-select
              @change="getInventoryBalanceData()"
            v-model="searchData.erpAreaId"
            filterable
            placeholder="请选择仓库"
            clearable
          >
            <el-option
              v-for="(item,key) in areaArr"
              :key="key"
              :label="item.areaName"
              :value="item.erpAreaId"
            >
            </el-option>
          </el-select>
        </div>
<!--        <div>-->
<!--          <span>容器号</span>-->
<!--          <el-input v-model="searchData.boxCode" size="mini" placeholder="容器号" clearable></el-input>-->
<!--        </div>-->
        <div>
          <span>批次号</span>
          <el-input v-model="searchData.batchName" size="mini" placeholder="批次号" clearable></el-input>
        </div>
        <div style="float: right">
          <el-button @click="download" size="mini" type="info" icon="el-icon-message" >导出</el-button>
        </div>
      </div>
      <span
        class="moreSearchBtn"
        :class="isMoreSearch ? 'el-icon-caret-top' : 'el-icon-caret-bottom'"
        @click="isMoreSearch = !isMoreSearch"
      ></span>
    </div>

    <div class="headerBtns">
      <el-button
        size="small"
        type="danger"
        round
        icon="iconfont icon-user-jinyong"
        @click="showFreezeModal"
        :disabled="isFreezeBtn"
      >冻结库存</el-button>
    </div>

    <el-dialog
      title="新增冻结单"
      :visible.sync="dialogFreezeVisible"
      :before-close="handleClose"
      width="900px"
      style="margin-top: -10vh"
    >
      <div class="packMasterBox">
        <el-form
          class="clearFloat"
          :model="form.freezeMaster"
          :rules="rules"
          ref="form.freezeMaster"
        >
          <el-form-item label="冻结原因" prop="freezeDescribe" :label-width="formLabelWidth">
            <el-select v-model="form.freezeMaster.freezeDescribe" filterable placeholder="请选择冻结原因">
              <el-option
                v-for="item in freezeReasons"
                :key="item.dictKey"
                :label="item.dictValue"
                :value="item.dictKey"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="备注" :label-width="formLabelWidth">
            <el-input v-model="form.freezeMaster.memo" placeholder="请输入备注"></el-input>
          </el-form-item>
        </el-form>
        <div class="tableBox noHeight">
          <el-table
            highlight-current-row
            :data="form.freezeDetails"
            max-height="360"
            style="width: 100%"
          >
            <el-table-column fixed="left" type="index" width="50"></el-table-column>
            <el-table-column
              fixed="left"
              sortable
              show-overflow-tooltip
              prop="itemName"
              label="物料名称"
            ></el-table-column>
            <el-table-column sortable show-overflow-tooltip prop="quantity" label="数量">
<!--              <template slot-scope="scope">-->
<!--                <span>-->
<!--                  {{-->
<!--                  Math.floor(-->
<!--                  (scope.row.quantity / scope.row.transRatio) * 10000-->
<!--                  ) / 10000-->
<!--                  }}-->
<!--                </span>-->
<!--              </template>-->
            </el-table-column>
            <el-table-column sortable show-overflow-tooltip prop="nowFreezeQuantity" label="已冻结数量">
<!--              <template slot-scope="scope">-->
<!--                <span>-->
<!--                  {{-->
<!--                  Math.floor(-->
<!--                  (scope.row.nowFreezeQuantity / scope.row.transRatio) * 10000-->
<!--                  ) / 10000-->
<!--                  }}-->
<!--                </span>-->
<!--              </template>-->
            </el-table-column>
            <el-table-column show-overflow-tooltip label="冻结数量">
<!--              <template slot-scope="scope">-->
<!--                <input-->
<!--                  type="number"-->
<!--                  class="my_input small"-->
<!--                  v-model.number="-->
<!--                    form.freezeDetails[scope.$index].freezeQuantity-->
<!--                  "-->
<!--                  :max="scope.row.quantity - scope.row.nowFreezeQuantity"-->
<!--                  placeholder="冻结数量"-->
<!--                  style="width: 80%"-->
<!--                />-->
<!--                &lt;!&ndash;                <el-input-number v-model="form.freezeDetails[scope.$index].freezeQuantity" controls-position="right" :min="0" :max="scope.row.quantity - scope.row.nowFreezeQuantity" style="width: 90%;"></el-input-number>&ndash;&gt;-->
<!--              </template>-->
            </el-table-column>
            <el-table-column sortable show-overflow-tooltip prop="packDescribe" label="单位"></el-table-column>
            <el-table-column sortable show-overflow-tooltip prop="batchName" label="批次"></el-table-column>
            <el-table-column sortable show-overflow-tooltip prop="itemCode" label="物料编码"></el-table-column>
            <el-table-column sortable show-overflow-tooltip prop="allotQuantity" label="分配数量">
<!--              <template slot-scope="scope">-->
<!--                <span>-->
<!--                  {{-->
<!--                  Math.floor(-->
<!--                  (scope.row.allotQuantity / scope.row.transRatio) * 10000-->
<!--                  ) / 10000-->
<!--                  }}-->
<!--                </span>-->
<!--              </template>-->
            </el-table-column>
            <el-table-column sortable show-overflow-tooltip prop="wareName" label="仓库"></el-table-column>
            <el-table-column sortable show-overflow-tooltip prop="cellCode" label="货位"></el-table-column>
            <el-table-column sortable show-overflow-tooltip prop="boxCode" label="追踪号"></el-table-column>
            <el-table-column sortable show-overflow-tooltip prop="lpn" label="LPN码"></el-table-column>
            <el-table-column fixed="right" label="操作">
              <template slot-scope="scope">
                <el-button
                  @click="deleteDetail(scope.$index)"
                  icon="iconfont icon-shanchu"
                  type="danger"
                  circle
                  plain
                  size="small"
                ></el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button
          class="leftFloat"
          type="primary"
          plain
          @click="commitForm('form.freezeMaster', -2)"
        >保存为草稿</el-button>
        <el-button
          @click="
            resetForm('form.freezeMaster');
            dialogFreezeVisible = false;
          "
        >取 消</el-button>
        <el-button type="primary" @click="commitForm('form.freezeMaster', 0)">确 定</el-button>
      </div>
    </el-dialog>

    <div class="tableBox rowHeight">
      <el-table
        v-loading="tableLoading"
        highlight-current-row
        :data="inventoryBalances"
        @selection-change="handleSelectionChange"
        style="width: 100%"
      >
        <el-table-column fixed="left" type="selection" width="55"></el-table-column>

        <el-table-column
          fixed="left"
          prop="inventoryId"
          label="库存ID"
          width="80"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column fixed="left" prop="itemName" label="物料名称" show-overflow-tooltip>
          <template slot-scope="scope">
            <span
              class="textBtn"
              @click="
                $EventBus.$emit('showPublicModal', scope.row.itemCode, 'item')
              "
            >{{ scope.row.itemName }}</span>
          </template>
        </el-table-column>
        <el-table-column show-overflow-tooltip prop="itemCode" label="物料编码">
          <template slot-scope="scope">
            <span
              class="textBtn"
              @click="
                $EventBus.$emit('showPublicModal', scope.row.itemCode, 'item')
              "
            >{{ scope.row.itemCode }}</span>
          </template>
        </el-table-column>
        <el-table-column show-overflow-tooltip prop="cellCode" label="货位"></el-table-column>
        <el-table-column show-overflow-tooltip prop="boxCode" label="追踪号"></el-table-column>
        <!--  <el-table-column

            show-overflow-tooltip
            prop="wareName"
            label="仓库"
            width="130">
            <template slot-scope="scope">
              <span class="textBtn" @click="$parent.showPublicModal(scope.row.wareId, 'ware')">{{scope.row.wareName}}</span>
            </template>
        </el-table-column>-->
        <el-table-column show-overflow-tooltip prop="confirmUserName" label="上架人">
<!--          <template slot-scope="scope">-->
<!--            <span-->
<!--              class="textBtn"-->
<!--              @click="-->
<!--                $EventBus.$emit(-->
<!--                  'showPublicModal',-->
<!--                  scope.row.organizationId,-->
<!--                  'organization'-->
<!--                )-->
<!--              "-->
<!--            >{{ scope.row.organizationName }}</span>-->
<!--          </template>-->
        </el-table-column>
        <el-table-column show-overflow-tooltip prop="batchName" label="批次">
          <template slot-scope="scope">
            <span
              class="textBtn"
              @click="
                $EventBus.$emit('showPublicModal', scope.row.batchId, 'batch')
              "
            >{{ scope.row.batchName }}</span>
          </template>
        </el-table-column>
        <el-table-column show-overflow-tooltip prop="quantity" label="数量">
<!--          <template slot-scope="scope">-->
<!--            <span style="color: black; font-weight: 900">-->
<!--              {{-->
<!--              Math.floor(-->
<!--              (scope.row.quantity / scope.row.transRatio) * 10000-->
<!--              ) / 10000-->
<!--              }}-->
<!--            </span>-->
<!--            <span style="font-size: 20%">（{{ scope.row.packDescribe }}）</span>-->
<!--          </template>-->
        </el-table-column>

        <!-- 钢材库DEMO -->
        <!-- <el-table-column show-overflow-tooltip prop="model" label="长">
        </el-table-column>
        <el-table-column show-overflow-tooltip prop="spec" label="宽">
        </el-table-column>
        <el-table-column show-overflow-tooltip prop="imgUrl" label="厚">
        </el-table-column>
        <el-table-column show-overflow-tooltip prop="lpn" label="是否冻结">
        </el-table-column>-->

        <el-table-column show-overflow-tooltip prop="allotQuantity" label="分配数量">
<!--          <template slot-scope="scope">-->
<!--            <span style="color: black; font-weight: 900">-->
<!--              {{-->
<!--              Math.floor(-->
<!--              (scope.row.allotQuantity / scope.row.transRatio) * 10000-->
<!--              ) / 10000-->
<!--              }}-->
<!--            </span>-->
<!--            <span style="font-size: 20%">（{{ scope.row.packDescribe }}）</span>-->
<!--          </template>-->
        </el-table-column>
        <el-table-column show-overflow-tooltip prop="freezeQuantity" label="冻结数量">
<!--          <template slot-scope="scope">-->
<!--            <span style="color: black; font-weight: 900">-->
<!--              {{-->
<!--              Math.floor(-->
<!--              (scope.row.freezeQuantity / scope.row.transRatio) * 10000-->
<!--              ) / 10000-->
<!--              }}-->
<!--            </span>-->
<!--            <span style="font-size: 20%">（{{ scope.row.packDescribe }}）</span>-->
<!--          </template>-->
        </el-table-column>
        <el-table-column show-overflow-tooltip prop="areaName" label="仓库"></el-table-column>
      </el-table>
      <el-pagination
        class="pagination-bottom"
        style="text-align: right"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
        :page-sizes="[15, 30, 50, 100]"
        :current-page.sync="searchData.pageNum"
        :page-size="searchData.pageSize"
        layout="sizes, total, prev, pager, next, jumper"
        :total="searchData.total"
      ></el-pagination>
    </div>
  </div>
</template>

<script>
export default {
  name: "InventoryBalance",
  data() {
    return {
      isMoreSearch: false,
      tableLoading: false,
      searchData: {
        erpAreaId: '',
        pageNum: 1,
        pageSize: 15,
        total: null,
        keyWords: "",
        wareId: PF.getLocal("wareId", "number"),
        organizationId: null,
        itemName: "",
        itemCode: "",
        cellCode: "",
        boxCode: "",
        batchName: "",
        cellUseType: "2"
      },

      inventoryBalances: [],
      organizations: [],
      multipleSelection: [],
      freezeReasons: [],
      areaArr:[],
      dialogNewVisible: false,
      dialogUpdateVisible: false,
      dialogFreezeVisible: false,

      formLabelWidth: "120px",

      form: {
        freezeMaster: {
          freezeDescribe: "",
          memo: "",
          wareId: null,
          wareName: "",
          organizationId: null,
          organizationName: ""
        },
        freezeDetails: []
      },
      rules: {
        freezeDescribe: [
          { required: true, message: "请输入冻结原因", trigger: "blur" }
        ],
        memo: [{ required: true, message: "请输入备注", trigger: "blur" }]
      }
    };
  },
  computed: {
    isFreezeBtn() {
      if (this.multipleSelection.length <= 0) {
        return true;
      }
      let organizationId = this.multipleSelection[0].organizationId;
      for (let i = 0; i < this.multipleSelection.length; i++) {
        if (organizationId !== this.multipleSelection[i].organizationId) {
          return true;
        }
      }
      return false;
    }
  },
  methods: {

    download() {


      window.open(localStorage.getItem("baseIpPort")+`/wms/transfer/exportInventory?erpAreaId=`+this.searchData.erpAreaId,'_blank')

      // request({
      //   url: "Card/DownloadTemplateFile",
      //   method: "get",
      // }).then((res) => {
      //   let url = window.URL.createObjectURL(new Blob([res]))
      //   let link = document.createElement('a')
      //   link.style.display = 'none'
      //   link.href = url
      //   link.setAttribute('download', 'courman'  + '.xls')
      //   document.body.appendChild(link);
      //   link.click();
      // });

    },

    showUpdateModal() {
      IOT.getServerData('/area/infos/list', 'get', {pageNum: 0, pageSize: 9999}, (ret) => {
        if (ret.code === 200) {
          this.areaArr = ret.rows;
        } else {
          IOT.tips(ret.message || '服务器请求失败，稍后再试！', 'error');
        }
      });
    },
    handleSizeChange(val) {
      this.searchData.pageSize = val;
      this.getInventoryBalanceData();
    },
    handleCurrentChange(val) {
      this.pageNum = val;
      this.getInventoryBalanceData();
    },
    clearSearchData() {
      this.searchData.keyWords = "";
      this.searchData.organizationId = null;
      this.searchData.itemCode = null;
      this.searchData.itemName = null;
      this.searchData.cellCode = null;
    },
    getInventoryBalanceData() {
      let searchData = PF.JSON(this.searchData);
      if (!PF.isNull(searchData.itemCode)) {
        delete searchData.itemCode;
      }
      if (!PF.isNull(searchData.itemName)) {
        delete searchData.itemName;
      }
      if (!PF.isNull(searchData.cellCode)) {
        delete searchData.cellCode;
      }
      searchData.pageSize = searchData.pageSize;
      this.tableLoading = true;
      IOT.getServerData("/inventorys/list", "get", searchData, ret => {
        this.tableLoading = false;
        if (ret.code === 200) {
          let list = ret.rows;
          /*for(let i=0;i<list.length;i++){
            list[i].quantity2 = list[i].quantity;
            list[i].packDetailId2 = list[i].packDetailId;
          }*/
          this.inventoryBalances = list;
          this.searchData.total = ret.total;
          this.searchData.pageNum = ret.pageNumber;
        } else {
          IOT.tips(ret.message || "服务器请求失败，稍后再试！", "error");
        }
      });
    },
    handleClose(done) {
      this.resetForm("form.freezeMaster");
      this.dialogFreezeVisible = false;
    },
    resetForm(formName) {
      // 重置
      this.$refs[formName].resetFields();
    },
    showFreezeModal() {
      let list = PF.JSON(this.multipleSelection);
      this.form.freezeMaster.wareId = list[0].wareId;
      this.form.freezeMaster.wareName = list[0].wareName;
      this.form.freezeMaster.organizationId = list[0].organizationId;
      this.form.freezeMaster.organizationName = list[0].organizationName;

      for (let i = 0; i < list.length; i++) {
        list[i].nowFreezeQuantity = list[i].freezeQuantity;
        list[i].freezeQuantity = null;
      }
      this.form.freezeDetails = list;
      this.dialogFreezeVisible = true;
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    deleteDetail(index) {
      this.form.freezeDetails.splice(index, 1);
    },
    commitForm(formName, insertType) {
      let that = this;
      IOT.showOverlay("保存中，请稍等...");
      this.$refs[formName].validate(valid => {
        if (valid) {
          let form = this.form;
          if (form.freezeDetails.length <= 0) {
            IOT.tips("未选择库存,请重新选择！", "error", 1000, () => {
              IOT.hideOverlay();
            });
            return false;
          }
          for (let i = 0; i < form.freezeDetails.length; i++) {
            if (
              !PF.isNull(form.freezeDetails[i].freezeQuantity) &&
              form.freezeDetails[i].freezeQuantity <= 0
            ) {
              IOT.tips("数量需大于零！", "error", 1000, () => {
                IOT.hideOverlay();
              });
              return false;
            }

            // 主单位数量
            form.freezeDetails[i].freezeQuantity =
              form.freezeDetails[i].freezeQuantity *
              form.freezeDetails[i].transRatio;
          }

          form.insertType = insertType;

          IOT.getServerData("/freeze/masters/insert", "post", form, ret => {
            IOT.hideOverlay();

            if (ret.code === 200) {
              IOT.tips("保存成功！", "success", 1000, () => {
                that.getInventoryBalanceData();
              });
            } else {
              IOT.tips(ret.message || "服务器请求失败，稍后再试！", "error");
            }
          });
          this.resetForm("form.freezeMaster");
          this.dialogFreezeVisible = false;
        } else {
          IOT.hideOverlay();
          console.error("error submit!!");
          return false;
        }
      });
    },
    changePackDetailId(index) {
      /*let packDetailId = this.inventoryBalances[index].packDetailId;
      let packDetailId2 = this.inventoryBalances[index].packDetailId2;
      let quantity = this.inventoryBalances[index].quantity;
      let packDetails = this.inventoryBalances[index].packDetails;
      let oldTransRatio = 0;
      let nowTransRatio = 0;
      for(let i=0;i<packDetails.length;i++){
        if(packDetailId === oldPackDetailId){
          nowTransRatio = oldTransRatio = 1;
        }else if(packDetails[i].packDetailId1 === packDetailId){
          oldTransRatio = packDetails[i].transRatio
        }else if(packDetails[i].packDetailId1 === packDetailId2){
          nowTransRatio = packDetails[i].transRatio
        }
      }
      let quantity2 = (quantity / oldTransRatio) * nowTransRatio;
      this.inventoryBalances[index].quantity2 = quantity2;*/

      let detail = PF.JSON(this.inventoryBalances[index]);
      for (let i = 0; i < detail.packDetails.length; i++) {
        if (detail.packDetails[i].packDetailId1 === detail.packDetailId) {
          this.inventoryBalances[index].packDescribe =
            detail.packDetails[i].packDescribe1;
          this.inventoryBalances[index].transRatio =
            detail.packDetails[i].transRatio1;
        }
      }
    }
  },
  created() {
    this.showUpdateModal();
    // this.getInventoryBalanceData();
    PF.getDataDictUdfData("freeze_reason", rows => {
      this.freezeReasons = rows;
    });
    PF.getOrganizations(rows => {
      this.organizations = rows;
    });
  },
  mounted() {}
};
</script>

<style scoped lang="less">
.inventoryBalance {
}
</style>
